package com.wing.qualityTesting.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.Idempotent;
import com.wing.qualityTesting.model.entity.ProcessQualityValue;
import com.wing.qualityTesting.model.request.ProcessQualityValueForm;
import com.wing.qualityTesting.model.response.ProcessQualityVO;
import com.wing.qualityTesting.service.ProcessQualityValueService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.qualityTesting.model.entity.ProcessQuality;
import com.wing.qualityTesting.model.request.ProcessQualityForm;
import com.wing.qualityTesting.service.ProcessQualityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-质量参数管理", tags = "#/qualityTesting/processQuality")
@RestController("processQualityController")
@RequestMapping("qualityTesting/admin/processQuality")
@RequiredArgsConstructor
public class ProcessQualityController {

    private final ProcessQualityService processQualityService;

    private final ProcessQualityValueService processQualityValueService;



    @ApiOperation(value = "查询所有质量参数", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProcessQualityVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
    ){

        Page<ProcessQuality> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        IPage<ProcessQualityVO> list = processQualityService.pageList4app(pg,paramMap);
        for (ProcessQualityVO record : list.getRecords()) {
            QueryWrapper<ProcessQualityValue> queryWrapper = new QueryWrapper();
            queryWrapper.eq("process_quality_id",record.getId());
            List<ProcessQualityValue> list1 = processQualityValueService.list(queryWrapper);
            List<String> nameList = list1.stream().map(ProcessQualityValue::getProcessQualityValue).collect(Collectors.toList());
            record.setProcessQualityValue(nameList);
        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加质量参数", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @Idempotent(keyPrefix = "processQualityAdd")
    public JsonResult add(@Validated(ProcessQualityForm.Add.class) ProcessQualityForm processQualityForm) {
        QueryWrapper<ProcessQuality> qualityQueryWrapper = new QueryWrapper<>();
        qualityQueryWrapper.eq("product_type_id",processQualityForm.getProductTypeId());
        qualityQueryWrapper.eq("category_id",processQualityForm.getCategoryId());
        qualityQueryWrapper.eq("process_id",processQualityForm.getProcessId());
        qualityQueryWrapper.eq("name",processQualityForm.getName());
        List<ProcessQuality> list = processQualityService.list(qualityQueryWrapper);
        if(list.size()>0){
            return JsonResult.fail("添加失败,拥有重复的参数名");
        }
        if (processQualityService.add(processQualityForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改质量参数", notes = "修改")
    @PutMapping("/update")
    @Idempotent(keyPrefix = "processQualityUpdate")

    public JsonResult update(@Validated(ProcessQualityForm.Update.class) ProcessQualityForm processQualityForm) {
        QueryWrapper<ProcessQuality> qualityQueryWrapper = new QueryWrapper<>();
        qualityQueryWrapper.eq("product_type_id",processQualityForm.getProductTypeId());
        qualityQueryWrapper.eq("category_id",processQualityForm.getCategoryId());
        qualityQueryWrapper.eq("process_id",processQualityForm.getProcessId());
        qualityQueryWrapper.eq("name",processQualityForm.getName());
        List<ProcessQuality> list = processQualityService.list(qualityQueryWrapper);
        if(list.size()>1){
            return JsonResult.fail("修改失败,拥有重复的参数名");
        }
        ProcessQuality processQuality = processQualityService.getById(processQualityForm.getId());
        if(processQuality == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProcessQuality.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(processQualityForm, processQuality, copyOptions);
        if (processQualityService.updateById(processQuality)) {
            // 修改value
            QueryWrapper<ProcessQualityValue> queryWrapper = new QueryWrapper<ProcessQualityValue>();
            queryWrapper.eq("process_quality_id",processQuality.getId());
            processQualityValueService.remove(queryWrapper);
            if(processQualityForm.getProcessQualityValue() != null){
                for (String value : processQualityForm.getProcessQualityValue()) {
                    ProcessQualityValueForm processQualityValueForm = new ProcessQualityValueForm();
                    processQualityValueForm.setProcessQualityValue(value);
                    processQualityValueForm.setProcessQualityId(processQuality.getId());
                    processQualityValueService.add(processQualityValueForm);
                }
            }
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除质量参数", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "processQualityId", value = "质量参数id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long processQualityId) {
        if (processQualityService.removeById(processQualityId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
